import socket
import threading
import time

class ChatClient:
    def __init__(self, host='47.94.52.200', port=8080):
        self.host = host
        self.port = port
        self.socket = None
        self.username = None
        self.running = False
        
    def connect(self, username):
        """连接到服务器并登录"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.host, self.port))
            self.username = username
            self.running = True
            
            # 发送登录消息
            self.send_message("LOGIN", "", "")
            
            # 启动接收消息的线程
            receive_thread = threading.Thread(target=self.receive_messages)
            receive_thread.daemon = True
            receive_thread.start()
            
            return True
        except Exception as e:
            print(f"连接失败: {e}")
            return False
            
    def disconnect(self):
        """断开与服务器的连接"""
        if self.running:
            self.running = False
            self.send_message("LOGOUT", "", "")
            self.socket.close()
            print("已断开连接")
            
    def send_message(self, message_type, receiver, content):
        """向服务器发送消息"""
        message = f"{message_type}|{self.username}|{receiver}|{content}"
        try:
            self.socket.send(message.encode('utf-8'))
        except Exception as e:
            print(f"发送消息失败: {e}")
            self.running = False
            
    def receive_messages(self):
        """接收并处理来自服务器的消息"""
        while self.running:
            try:
                data = self.socket.recv(1024)
                if not data:
                    print("服务器关闭连接")
                    self.running = False
                    break
                    
                message = data.decode('utf-8')
                self.handle_message(message)
            except Exception as e:
                if self.running:
                    print(f"接收消息出错: {e}")
                self.running = False
                break
                
    def handle_message(self, message):
        """处理接收到的消息"""
        try:
            parts = message.split('|', 3)
            if len(parts) < 4:
                print(f"无效消息格式: {message}")
                return
                
            message_type, sender, receiver, content = parts
            
            if message_type == "LOGIN":
                print(f"登录成功: {content}")
            elif message_type == "LOGOUT":
                print(f"用户 {sender} 已退出")
            elif message_type == "PRIVATE":
                print(f"来自 {sender} 的私信: {content}")
            elif message_type == "BROADCAST":
                print(f"{sender}: {content}")
            elif message_type == "ERROR":
                print(f"错误: {content}")
            else:
                print(f"未知消息类型: {message_type}")
        except Exception as e:
            print(f"处理消息出错: {e}")
            
    def send_broadcast(self, content):
        """发送广播消息"""
        self.send_message("BROADCAST", "", content)
        
    def send_private(self, receiver, content):
        """发送私信"""
        self.send_message("PRIVATE", receiver, content)

# 简单的命令行界面
def main():
    print("=== 聊天客户端 ===")
    username = input("请输入用户名: ")
    
    client = ChatClient()
    if not client.connect(username):
        return
        
    print("输入 '/q' 退出")
    print("输入 '/p 用户名 消息' 发送私信")
    print("直接输入内容发送广播消息")
    
    # 启动输入线程
    def input_loop():
        while client.running:
            try:
                message = input()
                if message == '/q':
                    client.disconnect()
                    break
                elif message.startswith('/p '):
                    parts = message.split(' ', 2)
                    if len(parts) < 3:
                        print("格式错误: /p 用户名 消息")
                        continue
                    receiver, content = parts[1], parts[2]
                    client.send_private(receiver, content)
                else:
                    client.send_broadcast(message)
            except KeyboardInterrupt:
                client.disconnect()
                break
                
    input_thread = threading.Thread(target=input_loop)
    input_thread.daemon = True
    input_thread.start()
    
    # 主线程等待
    while client.running:
        time.sleep(0.1)
        
if __name__ == "__main__":
    main()